<template>
    <div>
    <van-nav-bar title="注册账号" left-text="返回" left-arrow @click-left="onClickLeft" class="registerhedaer" />
    <van-form @submit="onSubmit" class="">
      <van-cell-group inset>
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import axios from 'axios';
import axiosInstance from './../axios/req'
import { showNotify } from 'vant';
import { showDialog } from 'vant';

const router = useRouter();
const username = ref('');
const password = ref('');
/**
 * 注册事件
 * @param values 表单参数对象
 */
 const onSubmit = (values) => {
console.log("1");
console.log('submit', values);
const user = {
    name: username.value,
    password: password.value,
  }
  const userJSON = JSON.stringify(user)
   //发送请求提交表单
   axiosInstance.post('addUser', userJSON)
    .then(res => {
      console.log(res);
      if (res.data.code == 200) {
        showDialog({
          title: '注册成功',
          message: '您的账号为：'+res.data.data.name+"请保存，使用账号登录",
        }).then(() => {
          // on close
          router.push('/');
        });
      }
    })
    .catch(err => {
      console.log(err);

      // 危险通知
      showNotify({ type: 'danger', message: err.response.data.message });

    })
};
/**
* 返回上一级
*/
const onClickLeft = () => {
history.back();
}
</script>